<template>
  <tm-app>
    <!-- 头部导航栏 -->
    <tm-navbar title="表单查看" :shadow="0">
    </tm-navbar>

    <!-- 筛选条件 -->
    <tm-sticky :offset="0" v-if="filterMenus.length > 0">
      <template v-slot:sticky>
        <tm-sheet :margin="[0, 0]" :padding="[32, 24]" :shadow="0" :round="0">
          <view class="filter-row">
            <view class="filter-item" v-for="item in displayFilterMenus" :key="item.type" @click="clickFilterDrawer(filterMenus.findIndex(menu => menu.type === item.type))">
              <text class="filter-text" :class="{ 'filter-text-active': hasSelectedOptions(filterMenus.findIndex(menu => menu.type === item.type)) }">{{ getFilterDisplayText(item) }}</text>
              <tm-icon name="tmicon-angle-down" :font-size="24"></tm-icon>
            </view>
          </view>
        </tm-sheet>
      </template>
    </tm-sticky>

    <!-- 资产卡片列表 -->
    <scroll-view
      scroll-y
      @scrolltolower="onLoadMore"
      style="height: 80vh;"
    >
      <tm-sheet :margin="[5, 5]" :padding="[0, 0]" :shadow="0" color="#f5f5f5" v-if="assetList&&assetList.length>0">
        <tm-sheet v-for="(item, index) in assetList" :key="index" :margin="[0, 0,0,10]" :padding="[24, 24]" :round="10">
          <!-- 卡片信息 -->
          <view class="info-row">
            <text class="label">唯一标识:</text>
            <text class="value">{{ item.id }}</text>
          </view>
          <template v-for="(cur,index) in assetField" :key="cur.id">
            <view class="info-row" v-if="index<4">
              <text class="label">{{cur.name}}:</text>
              <text class="value">{{ item[cur.id]??item['T'+cur.id]??item[cur.propId]??item['T'+cur.propId] }}</text>
            </view>
          </template>
          <!-- 查看详情按钮 -->
          <view class="detail-btn" @click="viewDetail(item)">
            <image src="/static/details.svg" style="width: 32rpx; height: 32rpx;"></image>
            <text class="btn-text">查看详情</text>
          </view>
        </tm-sheet>
      </tm-sheet>
      <tm-result v-else :showBtn="false"></tm-result>
      <view class="load-more" v-if="assetList && assetList.length > 0">
        <text>{{ hasMore ? '加载中...' : '没有更多数据了' }}</text>
      </view>
    </scroll-view>

    <!-- 统一筛选器 -->
    <tm-drawer
      v-model:show="showFilterDrawer"
      :hideHeader="true"
      placement="bottom"
      :height="1000"
      :round="12"
    >
      <view class="filter-drawer">
        <!-- 头部 -->
        <view class="filter-header">
          <tm-icon name="tmicon-close" :font-size="32" @click="showFilterDrawer = false"></tm-icon>
          <text class="filter-title">全部筛选</text>
          <tm-icon name="tmicon-close" :font-size="32" @click="showFilterDrawer = false"></tm-icon>
        </view>

        <!-- 内容区 -->
        <view class="filter-content">
          <!-- 左侧筛选条件列表 -->
          <view class="filter-menu">
            <view
              v-for="(item, index) in filterMenus"
              :key="index"
              class="filter-menu-item"
              :class="{ active: currentFilterIndex === index }"
              @click="clickCurrentFilter(index)"
            >
              <text>{{ item.title }}</text>
            </view>
          </view>

          <!-- 右侧内容区 -->
          <view class="filter-detail">
            <text class="detail-title">{{ filterMenus[currentFilterIndex]?.title }}</text>
            <!-- 选项列表类型 -->
            <template v-if="filterMenus[currentFilterIndex]?.filterType === 'select'">
              <!-- 选项列表 -->
              <template v-if="showCascader">
                <tm-cascader
                  ref="textCascader"
                  @cell-click="test"
                  v-model="testValue"
                  :defaultValue="testValue"
                  :data="filterMenus[currentFilterIndex].options"
                ></tm-cascader>
              </template>
            </template>
            <!-- <template v-if="filterMenus[currentFilterIndex]?.filterType === 'user'">
              <view class="search-box">
                <tm-input v-model="searchKey" @input="searchInfo" :searchWidth="120" prefix="tmicon-search" :placeholder="`搜索${filterMenus[currentFilterIndex]?.title}`"></tm-input>
              </view>
              <scroll-view class="option-list" scroll-y>
                <view
                  v-for="(option, idx) in filterMenus[currentFilterIndex]?.options"
                  :key="idx"
                  class="option-item"
                  :class="{ active: option.selected }"
                  @click="selectOption(option)"
                >
                  <view class="option-content">
                    <tm-avatar
                      v-if="option.avatar"
                      :src="option.avatar"
                      :size="64"
                      :round="3"
                    ></tm-avatar>
                    <view class="option-text">
                      <text class="option-title">{{ option.title }}</text>
                      <tm-tag text outlined color="#0052d9" size="s" label="单位"></tm-tag>
                      <br>
                      <text v-if="option.description" class="option-desc">{{ option.description }}</text>
                    </view>
                  </view>
                  <tm-icon
                    v-if="option.selected"
                    name="tmicon-check-circle-filled"
                    :font-size="32"
                    color="primary"
                  ></tm-icon>
                </view>
              </scroll-view>
            </template> -->
            <!-- 文本和数字输入类型 -->
            <template v-if="filterMenus[currentFilterIndex]?.filterType === 'input'">
              <view class="input-box">
                <tm-input
                  v-model="filterMenus[currentFilterIndex].inputValue"
                  :placeholder="`请输入${filterMenus[currentFilterIndex]?.title}`"
                  :searchWidth="120"
                ></tm-input>
              </view>
            </template>
            <!-- 日期和时间输入类型 -->
            <template v-if="filterMenus[currentFilterIndex]?.filterType === 'date'">
              <view class="input-box">
                <tm-input
                  v-model="filterMenus[currentFilterIndex].inputValue"
                  :placeholder="`请选择${filterMenus[currentFilterIndex]?.title}`"
                  :searchWidth="120"
                  @click="showTimePicker = true"
                ></tm-input>
              </view>
            </template>
          </view>
        </view>
        <!-- 底部按钮 -->
        <view class="filter-footer">
          <tm-button size="large" color="#E7E7E7" @click="clearAllSelections">清空选择</tm-button>
          <tm-button size="large" color="#0052D9" @click="confirmFilter">筛选·{{ selectedCount }}</tm-button>
        </view>
      </view>
    </tm-drawer>
    <tm-time-picker
      v-model:show="showTimePicker"
      v-model="currentDate"
      :defaultValue="currentDate"
      v-model:model-str="currentSar"
      format="YYYY/MM/DD"
      @confirm="handleTimeConfirm"
      @change="handleTimeChange"
      :showDetail="{year: true,month: true,day: true}"
    />
  </tm-app>
</template>

<script lang="ts" setup>

import { computed, getCurrentInstance, nextTick, onMounted, ref } from 'vue'
import { IForm } from '@/ts/core';
import { userFormatFilter,buildTree } from '@/utils/tools'
import { formatDate } from '@/utils'
import { XThing } from '@/ts/base/schema'
import { getWidget } from '@/utils/work'
import { FieldModel } from '@/ts/base/model'
import { FilterMenu } from '@/pages/open/config'
// 筛选器相关
const showFilterDrawer = ref(false)
const currentFilterIndex = ref(0)
const searchKey = ref('')
const curForm = ref<IForm>()
const fieldData = ref<FieldModel[]>([])
const filterOption = ref()
const hasMore = ref(true)// 是否还有更多数据
const showTimePicker = ref(false)
const currentDate = ref('2025/7/10')
const currentSar = ref('')
const testValue = ref([])
const showCascader = ref(true)
// 资产列表数据
const assetList = ref<XThing[]>([
])
// 筛选菜单数据
const filterMenus = ref<FilterMenu[]>([
  {
    title: '唯一标识',
    type: 'id',
    filterType: 'input',
    inputValue: '',
    options: []
  }
])
const assetField = ref<FieldModel[]>([])
const menuType = ['数字框','文本框','单选框','多级选择框','日期选择框','时间选择框']//'人员搜索框'
const widgetTypeMap = {
  '文本框': 'input',
  '数字框': 'input',
  '单选框': 'select',
  '多级选择框': 'select',
  '日期选择框': 'date',
  '时间选择框': 'date'
}
//请求相关初始参数
const loadOptions:any = {
  filter:undefined,
  requireTotalCount: true,
  searchOperation: 'contains',
  searchValue: null,
  skip: 0,
  take: 20,
  userData: {},
  sort: [
    {
      selector: 'id',
      desc: false
    }
  ],
  group: null
}

const test = (item: any) => {
  filterMenus.value[currentFilterIndex.value].inputValue = item.value
}
onMounted(() => {
  uni.showLoading({ title: '加载中...' })
  const instance = getCurrentInstance()!.proxy
  const eventChannel = instance!.getOpenerEventChannel();
  eventChannel.on('formData', async (data) => {
    curForm.value = data.data
    await loadContent()
    uni.hideLoading()
  })
})
const handleTimeChange = (e: string) => {
  currentSar.value = e
}
const handleTimeConfirm = () => {
  if (!currentSar.value && currentDate.value) {
    const date = new Date(currentDate.value)
    currentSar.value = `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`
  }
  filterMenus.value[currentFilterIndex.value].inputValue = currentSar.value+' 00:00:00'
  showTimePicker.value = false
}
const getFilterMenuConfig = (item) => {
  const widgetType = getWidget(item.valueType, item.widget)
  const filterType = widgetTypeMap[widgetType]
  
  const baseConfig = {
    title: item.name,
    type: item.code,
    filterType
  }

  if (filterType === 'input') {
    return {
      ...baseConfig,
      inputValue: '',
      options: []
    }
  }
  
  if (filterType === 'select') {
    const options = widgetType === '单选框' 
      ? (item.lookups?.length ? item.lookups : [])
      : (item.lookups?.length ? buildTree(item.lookups) : [])
    
    return {
      ...baseConfig,
      fileds: item.lookups ?? [],
      options
    }
  }
  
  return {
    ...baseConfig,
    options: []
  }
}
const loadContent = async (curLoadOptions?:any) =>{
  if(!curForm.value)return false
  const fields = await curForm.value.loadFields()
  fieldData.value = fields
  if(!curLoadOptions){
    //初始进来的情况
    loadOptions.filter = await userFormatFilter(loadOptions.filter, curForm.value);
    loadOptions.filter = curForm.value.parseFilter(loadOptions.filter);
    filterOption.value = loadOptions.filter
    const classify = curForm.value.parseClassify();
    if (loadOptions.filter.length === 0 && Object.keys(classify).length === 0) {
      //空数据
    }
    loadOptions.userData = [];
    const field = fields.filter((item)=>getWidget(item.valueType,item.widget)==='数字框'||getWidget(item.valueType,item.widget)==='文本框')
    const menus = fields.filter((item)=>menuType.includes(getWidget(item.valueType,item.widget)))
    menus.forEach(item => {
      filterMenus.value.push(getFilterMenuConfig(item))
    })
    assetField.value = field
  }else{
    //有过滤条件，或者做了加载更多的分页情况
    loadOptions.filter = curLoadOptions.filter
    loadOptions.skip = curLoadOptions.skip
  }
  const data = await curForm.value.loadThing(loadOptions)
  // 判断是否还有更多数据
  hasMore.value = data.data.length >= loadOptions.take
  assetList.value = [...assetList.value,...data.data]
}
// 上拉加载更多
const onLoadMore = async () => {
  // 如果没有更多数据，直接返回
  if (!hasMore.value) {
    return
  }
  // 修改分页参数
  loadOptions.skip += loadOptions.take
  await loadContent(loadOptions)
}
const selectedCount = computed(() => {
  return filterMenus.value.reduce((count, menu) => {
    return count + (menu.inputValue ? 1 : 0)
  }, 0)
})
const displayFilterMenus = computed(() => {
  // 将筛选条件分为已选中和未选中两组
  const selectedMenus = filterMenus.value.filter(menu => 
    menu.filterType === 'select' 
      ? menu.options?.some(option => option.selected)
      : !!menu.inputValue
  )
  const unselectedMenus = filterMenus.value.filter(menu => 
    menu.filterType === 'select'
      ? !menu.options?.some(option => option.selected)
      : !menu.inputValue
  )
  
  // 如果已选中的条件超过4个，只取前4个
  if (selectedMenus.length >= 4) {
    return selectedMenus.slice(0, 4)
  }
  
  // 否则，用未选中的条件补充到4个
  return [
    ...selectedMenus,
    ...unselectedMenus.slice(0, 4 - selectedMenus.length)
  ]
})
const getFilterDisplayText = (menu: FilterMenu) => {
  if (menu.filterType === 'select') {
    // 对于选项列表类型，如果有选中项则显示选中项的标题，否则显示原始标题
    const selectedOption = menu.fileds?.find(option => option.value === menu.inputValue)
    return selectedOption ? selectedOption.text : menu.title
  } else {
    // 对于输入类型，如果有输入值则显示输入值，否则显示原始标题
    return menu.inputValue || menu.title
  }
}
// 判断某个筛选条件是否有选中的选项
const hasSelectedOptions = (index: number) => {
  return !!filterMenus.value[index].inputValue // 文本输入类型，有值则认为已选择
}

// 选择筛选选项
// const selectOption = (option: Option) => {
//   console.log(option);
//   const currentMenu = filterMenus.value[currentFilterIndex.value]
  
//   // 清除所有选项的选中状态（包括子选项）
//   const clearSelection = (options: Option[]) => {
//     options.forEach(opt => {
//       opt.selected = false
//       if (opt.children) {
//         clearSelection(opt.children)
//       }
//     })
//   }
//   clearSelection(currentMenu.options)
//   option.selected = true
//   currentMenu.inputValue = option.value
// }
// 清空所有选择
const clearAllSelections = async () => {
  filterMenus.value.forEach(menu => {
    if (menu.filterType ==='select') {
      menu.options.forEach(option => {
        option.selected = false
      })
    }
    menu.inputValue = ''
  })
  currentFilterIndex.value = 0
  loadOptions.filter = filterOption.value
  loadOptions.skip = 0
  assetList.value = []
  showFilterDrawer.value = false
  await loadContent(loadOptions)
}
// 确认筛选
const confirmFilter = async () => {
  showFilterDrawer.value = false
  if (!loadOptions.filter) {
    loadOptions.filter = []
  }
  // TODO: 根据筛选条件筛选资产列表
  filterMenus.value.forEach(menu=>{
    //文字和数字还有多级选择框的筛选
    if(menu.inputValue && menu.filterType !== 'date'){
      // 查找是否已存在相同类型的数组
      const existingField = loadOptions.filter.find(
        field => Array.isArray(field) && field[0] === menu.type
      )
      if(menu.type === 'id'){
        if(existingField&&existingField[1] === 'contains') {
          // 更新现有数组的输入值
          existingField[2] = menu.inputValue
        } else {
          // 添加新数组
          loadOptions.filter = [[menu.type,'contains',menu.inputValue], 'and', ...loadOptions.filter]
        }
      }else{
        if(existingField) {
          // 更新现有数组的输入值
          existingField[2] = menu.inputValue
        } else {
          // 添加新数组
          loadOptions.filter = [[menu.type,'contains',menu.inputValue], 'and', ...loadOptions.filter]
        }
      }
      
    }else if(menu.filterType === 'date' && menu.inputValue){
      // 处理日期条件 - 生成时间范围条件
      const startDate = menu.inputValue; // 格式如 "2024/02/10 00:00:00"
      
      // 计算结束时间（当前日期+1天）
      const endDate = new Date(new Date(startDate).getTime() + 24 * 60 * 60 * 1000);
      const formattedEndDate = formatDate(endDate,'yyyy/MM/dd 00:00:00');
      // 创建时间范围条件数组
      const timeCondition = [
        [menu.type, '>=', startDate],
        'and',
        [menu.type, '<', formattedEndDate]
      ];
      // 查找是否已存在相同类型的时间范围条件
      let foundIndex = -1;
      let foundCount = 0;
      // 遍历查找相同类型的条件
      for (let i = 0; i < loadOptions.filter.length; i++) {
        const item = loadOptions.filter[i];
        
        // 检查是否匹配当前类型的时间条件
        if (Array.isArray(item) && item[0] === menu.type && 
            (item[1] === '>=' || item[1] === '<')) {
          
          // 记录第一个匹配的位置
          if (foundIndex === -1) foundIndex = i;
          foundCount++;
          
          // 如果已经找到两个条件（一个 >= 和一个 <），停止搜索
          if (foundCount === 2) break;
        }
      }
      // 如果找到完整的时间范围条件
      if (foundCount === 2 && foundIndex !== -1) {
        // 替换现有的时间范围条件
        loadOptions.filter.splice(foundIndex, 3, ...timeCondition);
      } else if (foundIndex !== -1) {
        // 只找到部分条件，移除不完整的条件
        for (let i = 0; i < foundCount; i++) {
          loadOptions.filter.splice(foundIndex, 1);
        }
        // 添加完整的时间范围条件
        loadOptions.filter = [...timeCondition, 'and', ...loadOptions.filter];
      } else {
        // 没有找到任何匹配条件，添加新条件
        loadOptions.filter = [...timeCondition, 'and', ...loadOptions.filter];
      }
    }
  })
  loadOptions.skip = 0
  assetList.value = []
  await loadContent(loadOptions)
}
// 查看详情
const viewDetail = (item: any) => {
  // 跳转到详情页面
  uni.navigateTo({
    url: '/pages/open/formInfo',
    success: function (res) {
      res.eventChannel.emit('formInfo', {
        localFormData: item,
        fields: fieldData.value
      })
    }
  })
}
const clickCurrentFilter = (index: number) => {
  //切换后搜索框清空
  searchKey.value = ''
  // 恢复原始选项切换前的数据
  const currentMenu = filterMenus.value[currentFilterIndex.value]
  if (currentMenu.originalOptions) {
    currentMenu.options = [...currentMenu.originalOptions]
  }
  testValue.value = []
  currentFilterIndex.value = index
  showCascader.value = false
  nextTick(() => {
    showCascader.value = true
  })
}
const clickFilterDrawer = (index: number) => {
  showFilterDrawer.value = true
  currentFilterIndex.value = index
  showCascader.value = true
}
// const searchInfo = (value: string) => {
//   const currentMenu = filterMenus.value[currentFilterIndex.value]
//   if (!currentMenu) return
  
//   // 如果搜索值为空，恢复原始选项
//   if (!value.trim()) {
//     currentMenu.options = currentMenu.originalOptions || []
//     return
//   }

//   // 如果是第一次搜索，保存原始数据
//   if (!currentMenu.originalOptions) {
//     currentMenu.originalOptions = [...currentMenu.options]
//   }

//   // 转换为小写进行不区分大小写的搜索
//   const searchValue = value.toLowerCase()
  
//   // 对每个选项进行评分并排序
//   currentMenu.options = currentMenu.originalOptions.filter(option => {
//     const titleMatch = option.title?.toLowerCase().includes(searchValue)
//     const descMatch = option.description?.toLowerCase().includes(searchValue)
    
//     // 如果标题或描述中包含搜索词则显示
//     // title 匹配优先级更高
//     return titleMatch || descMatch
//   }).sort((a, b) => {
//     const aTitle = a.title?.toLowerCase().includes(searchValue)
//     const bTitle = b.title?.toLowerCase().includes(searchValue)
//     const aDesc = a.description?.toLowerCase().includes(searchValue)
//     const bDesc = b.description?.toLowerCase().includes(searchValue)
    
//     // 标题匹配的排在前面
//     if (aTitle && !bTitle) return -1
//     if (!aTitle && bTitle) return 1
//     // 其次是描述匹配的
//     if (aDesc && !bDesc) return -1
//     if (!aDesc && bDesc) return 1
//     return 0
//   })
// }
</script>

<style lang="scss" scoped>
.load-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}
// 筛选条件样式
.filter-row {
  display: flex;
  align-items: center;
  width: 100%;
  border-bottom: 2rpx solid #f5f5f5;

  .filter-item {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    height: 80rpx;
    position: relative;

    &:not(:last-child)::after {
      content: '';
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 2rpx;
      height: 40rpx;
      background-color: #f5f5f5;
    }

    &.active {
      .filter-text {
        color: #0052d9;
      }
    }

    .filter-text {
      font-size: 28rpx;
      color: #333;
      margin-right: 8rpx;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .filter-text-active {
      color: #0052d9;
    }
  }
}
.filter-drawer {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;

  .filter-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
    border-bottom: 2rpx solid #f5f5f5;

    .filter-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }
  }

  .filter-content {
    flex: 1;
    display: flex;
    overflow: hidden;

    .filter-menu {
      width: 200rpx;
      height: 100%;
      background-color: #f5f5f5;
      overflow-y: auto;

      .filter-menu-item {
        padding: 32rpx 24rpx;
        font-size: 28rpx;
        color: #333;
        background-color: #f5f5f5;

        &.active {
          background-color: #fff;
          color: #0052d9;
        }
      }
    }

    .filter-detail {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 32rpx;
      overflow: hidden;

      .detail-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 24rpx;
      }

      .search-box {
        margin-bottom: 24rpx;
      }

      .option-list {
        flex: 1;
        overflow-y: auto;
        .sub-options {
          padding-left: 40rpx;
          
          .sub-item {
            border-left: 2rpx solid #f5f5f5;
          }
        }
        .sub-options {
          padding-left: 40rpx;
          
          .sub-item {
            border-left: 2rpx solid #f5f5f5;
          }
        }
        .option-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 24rpx 0;
          border-bottom: 2rpx solid #f5f5f5;
          .option-header {
            display: flex;
            align-items: center;
            gap: 8rpx;
          }
          &.active {
            .option-title {
              color: #0052d9;
            }
          }

          .option-content {
            display: flex;
            align-items: center;
            flex: 1;
            margin-right: 24rpx;

            .option-text {
              margin-left: 24rpx;

              .option-title {
                font-size: 28rpx;
                color: #333;
                margin-bottom: 8rpx;
              }

              .option-desc {
                font-size: 24rpx;
                color: #999;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
            }
          }
        }
      }
    }
  }
}

// 资产卡片样式
.info-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16rpx;
  
  .label {
    color: #666;
    font-size: 28rpx;
    margin-right: 20rpx;
  }
  
  .value {
    color: #333;
    font-size: 28rpx;
    flex: 1;
  }
}

.detail-btn {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 24rpx;
  padding-top: 24rpx;
  border-top: 2rpx solid #f5f5f5;
  
  .btn-text {
    color: #0052D9;
    font-size: 28rpx;
    margin-left: 8rpx;
  }
}
.filter-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-top: 2rpx solid #f5f5f5;
  
  :deep(.tm-button) {
    flex: 1;
    margin: 0 16rpx;
    
    &:first-child {
      margin-left: 0;
    }
    
    &:last-child {
      margin-right: 0;
    }
  }
}
</style>